<?php

namespace App\V3\V3_2_7\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\StorageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use App\V3\V3_2_7\Services\StorageService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_2_7\Models\AdminModel;

class StorageController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 13:50
     * @return JsonResponse
     */
    public function storageList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $userId = [];
        $storageIdArr = [];
        $data['keyword'] = empty($data['keyword'])?'':$data['keyword'];
        if($this->getUserId() == $this->getMainUserId()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if($this->isShareStorage()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $userInfo = [
                    'main_id' => $this->getMainUserId(),
                    'user_id' => $this->getUserId()
                ];
                $storageIdArr = CommonService::getMultiUser($userInfo);
                if(empty($storageIdArr)){
                    $userId['a.user_id'] = ['EQ' => $this->getUserId()];
                }
            }
        }

       $list = StorageModel::getStorageList($userId, $data, $storageIdArr);

        if(!empty($list['data'])){
            foreach ($list['data'] as &$val){
                $val['staff_list'] = [];
                if(!empty($val['multi_user_id'])){
                    $userIds = array_filter(explode(',',$val['multi_user_id']), function($v) { return $v !== '';});
                    $userList = AdminModel::select('id','nickname','username', 'position', 'mobile')
                    ->whereIn('id',$userIds)
                    ->get();
                    if(!empty($userList)){
                        $userList = $userList->toArray();
                        foreach ($userList as &$uVal){
                            $uVal['storage_name'] = $val['storage_name'];
                        }
                    }
                    $val['staff_list'] = !empty($userList)?$userList:[];
                }
            }
        }
        return $this->success($list);
    }

    /**
     * 下拉
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 13:55
     * @return JsonResponse
     */
    public function storageSelect(Request $request)
    {
        $isAllocate = empty($request->input('is_allocate','0'))?0:1;//是否为调拨使用;0:否;1:是;
        $userId = [];
        $storageIdArr = [];
        if(!$isAllocate) {
            if($this->getUserId() == $this->getMainUserId()) {
                $userId['main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                if($this->isShareStorageOperate()) {
                    $userId['main_id'] = ['EQ' => $this->getMainUserId()];
                }
                else {
                    $userInfo = [
                        'main_id' => $this->getMainUserId(),
                        'user_id' => $this->getUserId()
                    ];
                    $storageIdArr = CommonService::getMultiUser($userInfo);
                    if(empty($storageIdArr)){
                        $userId['user_id'] = ['EQ' => $this->getUserId()];
                    }
                }
            }
        }
        else {
            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
        }

        return $this->success(
            StorageModel::getStorageSelect($userId,$storageIdArr)
        );
    }

    /**
     * 新建
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 14:16
     * @return JsonResponse|void
     */
    public function add(Request $request)
    {
        if(empty($result = self::checkInfo($data = $request->all()))) {
            $data['storage_address'] = empty($data['storage_address'])?"":$data['storage_address'];
            if(empty($data['user_id'])) $data['user_id'] = 0;
            $adminName = AdminModel::where('id',$this->getUserId())->value('username');
            if($this->getUserTpye()) {//子账户添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $this->getUserId(),
                    'main_id' => $this->getMainUserId(),
                    'created_at' => time(),
                ];
                $logData = '子账户:'.$adminName.'添加仓库:'.$data['storage_name'].'已成功!';
            }
            else {//主账号添加仓库
                if(!empty($data['multi_user_id'])){
                    $name = '';
                    $userIdArr = array_filter(explode(',',$data['multi_user_id']), function($v) { return $v !== '';});
                     $storageList = StorageModel::select('multi_user_id as userIds')
                     ->where([
                         'delete_flag' => 0,
                         'main_id' => $this->getMainUserId()
                     ])->where('multi_user_id','!=','')
                     ->get()->toArray();
                     if(!empty($storageList)){
                         foreach ($storageList as $sVal){
                             $storageUserIdArr= array_filter(explode(',',$sVal['userIds']), function($v) { return $v !== '';});
                             $intersect=array_intersect($storageUserIdArr,$userIdArr);
                             if(!empty($intersect)){
                                 foreach ($intersect as $iVal){
                                     $userInfo = AdminModel::select('username','nickname')->where([
                                         'id' => $iVal
                                     ])->first();
                                     $userInfo['nickname']=!empty($userInfo['nickname'])?$userInfo['nickname']:$userInfo['username'];
                                     if($userInfo['delete_flag'] == 0){
                                         $name .= $userInfo['nickname'].',';
                                     }else{
                                         return response()->json(['code'=>1,'msg'=>'员工：'.$userInfo['nickname'].'信息不存在','data'=>'']);
                                     }
                                 }
                             }
                         }
                     }
                     if(!empty($name)){
                        return response()->json(['code'=>1,'msg'=>'员工：'.$name.'已添加，请重新选择其他员工！','data'=>'']);
                     }
                }
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => !empty($data['user_id'])?$data['user_id']:$this->getUserId(),
                    'main_id' => $this->getMainUserId(),
                    'created_at' => time(),
                    'multi_user_id'=>!empty($data['multi_user_id'])?$data['multi_user_id']:'',
                ];
                $logData = '主账户:'.$adminName.'添加仓库:'.$data['storage_name'].'已成功!';
            }

            $checkStorage = StorageModel::where([
                'storage_name' => $arr['storage_name'],
                /* 'storage_address' => $arr['storage_address'], */
                'main_id' => $arr['main_id'],
            ])
                ->where('delete_flag', 0)
                ->first();

            if(!empty($checkStorage)) {
                return $this->fail('', '仓库`'.$arr['storage_name'].'-'.$arr['storage_address'].'`已存在');
            }

            DB::beginTransaction();

            try {
                $insertId = StorageModel::insertGetId($arr);

                $shelfId = StorageShelfModel::insertGetId([
                    'main_id' => $this->getMainUserId(),
                    'storage_id' => $insertId,
                    'shelf_type' => 1,
                    'created_at' => time(),
                    'sort' => 1
                ]);

                StorageShelfLocationModel::insert([
                    'main_id' => $this->getMainUserId(),
                    'storage_id' => $insertId,
                    'shelf_id' => $shelfId,
                    'location_type' => 1,
                    'created_at' => time()
                ]);
                $this->log('添加仓库', $arr, $logData);
                DB::commit();
                return $this->success($insertId);
            }
            catch(Exception $e) {
               DB::rollBack();
               Log::debug('创建仓库异常：'.var_export($e->getMessage(), true));
               return $this->fail('', $e->getMessage());
            }
        }
        else {
            return $result;
        }
    }

    private function checkInfo($data)
    {
        //参数验证
        $validator = Validator::make(
            $data,
            [
                'storage_name' =>'required|string',//仓库名
//                'storage_address' =>'required',//仓库地址
                /* 'user_id' =>'required',//仓库负责人id */
            ],
            [
                'storage_name.required' => '请填写仓库名称',
                'storage_name.string' => '仓库名称不合法',
//                'storage_address.required' => '请填写仓库地址',
                /* 'user_id.required' => '请选择仓库负责人', */
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
    }

    public function edit(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//供应商客户表主键id
        ],
            [
                'id.required' => '参数`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(empty(self::checkInfo($data = $request->all()))) {
            $data['storage_address'] = empty($data['storage_address'])?"":$data['storage_address'];
            if(empty($data['user_id'])) $data['user_id'] = 0;
            $adminName = AdminModel::where('id',$this->getUserId())->value('username');
            if($this->getUserTpye()) {//子账户添加仓库
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $this->getUserId(),
                ];
                $logData = '子账户:'.$adminName.'仓库:'.$data['storage_name'].'信息已更新!';
            }else {//主账号添加仓库

                if(!empty($data['multi_user_id'])){
                    $name = '';
                    $userIdArr = array_filter(explode(',',$data['multi_user_id']), function($v) { return $v !== '';});
                    $storageList = StorageModel::select('multi_user_id as userIds')
                    ->where([
                        'delete_flag' => 0,
                        'main_id' => $this->getMainUserId()
                    ])->where('id','!=',$data['id'])
                    ->where('multi_user_id','!=','')
                    ->get()->toArray();
                    if(!empty($storageList)){
                        foreach ($storageList as $sVal){
                            $storageUserIdArr= array_filter(explode(',',$sVal['userIds']), function($v) { return $v !== '';});
                            $intersect=array_intersect($storageUserIdArr,$userIdArr);
                            if(!empty($intersect)){
                                foreach ($intersect as $iVal){
                                    $userInfo = AdminModel::select('username','nickname')->where([
                                        'id' => $iVal
                                    ])->first();
                                    $userInfo['nickname']=!empty($userInfo['nickname'])?$userInfo['nickname']:$userInfo['username'];
                                    if($userInfo['delete_flag'] == 0){
                                        $name .=$userInfo['nickname'].',';
                                    }else{
                                        return response()->json(['code'=>1,'msg'=>'员工：'.$userInfo['nickname'].'信息不存在','data'=>'']);
                                    }
                                }
                            }
                        }
                    }
                   /* if(!empty($name)){
                        return response()->json(['code'=>1,'msg'=>'员工：'.$name.'已添加，请重新选择其他员工！','data'=>'']);
                    }*/
                }
                $arr = [
                    'storage_name' => $data['storage_name'],
                    'storage_address' => $data['storage_address'],
                    'remarks' => empty($data['remarks'])?'':$data['remarks'],
                    'user_id' => $data['user_id'],
                    'multi_user_id'=>!empty($data['multi_user_id'])?$data['multi_user_id']:'',
                ];
                $logData = '主账户:'.$adminName.'仓库:'.$data['storage_name'].'信息已更新!';
            }

            $checkInfo = StorageModel::where([
                'storage_name' => $data['storage_name'],
                /* 'storage_address' => $data['storage_address'], */
                'main_id' => $this->getMainUserId(),
                'delete_flag' => 0
            ])->where('id', '!=', $data['id'])->first();

            if(!empty($checkInfo)) {
                return $this->fail('', '仓库:'.$data['storage_name'].'-'.$data['storage_address'].'已存在');
            }

            $isUpdate = StorageModel::where('id', $data['id'])
                ->lockForUpdate()
                ->update($arr);

            if($isUpdate !== false) {
                $this->log('修改仓库信息', array_merge($arr, $data), $logData);
                return $this->success(array_merge($arr, $data));
            }
        }
        else {
            return $this->fail('', self::checkInfo($request->all()));
        }
    }

    /**
     * 删除指定仓库信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/17 14:37
     * @return JsonResponse
     */
    public function delete(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//供应商客户表主键id
        ],
            [
                'id.required' => '参数`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $result = StorageService::delete($data);

        if($result['code']) {
            return $this->fail('',$result['msg']);
        }
        else {
            $this->log('删除仓库', $data, $result['data']);
            return $this->success();
        }
    }

    /**
     * 仓库货架库位三级列表
     * 2022/9/17 10:46
     * Author: Sun Wu
     * @return JsonResponse
     */
    public function storageShelfLocation(Request $request): JsonResponse
    {
        $data = [];
        $storageIdArr = [];
        if(empty($request->input('is_allocate'))) {
            if($this->getMainUserId() == $this->getUserId() || $this->isShareStorage()) {
                $data['main_id'] = $this->getMainUserId();
            }
            else {
                $userInfo = [
                    'main_id' => $this->getMainUserId(),
                    'user_id' => $this->getUserId()
                ];
                $storageIdArr = CommonService::getMultiUser($userInfo);
                if(empty($storageIdArr)){
                    $data['user_id'] = $this->getUserId();
                }
            }
        }
        else {
            $data['main_id'] = $this->getMainUserId();
        }

        return $this->success(
            StorageService::storageShelfLocation($data,$storageIdArr)
        );
    }

    /**
     *修改仓库员工
     * Author: zlf
     * Created at 2024/5/9 15:15
     * @param Request $request
     * @return void
     */
    public function editStorageStaff(Request $request)
    {
        //验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//仓库id
        ],
            [
                'id.required' => '参数仓库`id`丢失',
            ]
        );
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        if(!$request->has('multi_user_id')){
            return $this->fail('', '员工信息，不能存在！');
        }
        $data['main_id'] = $this->getMainUserId();
        return response()->json(StorageService::editStorageStaff($data));
    }
}
